package rexsee.core.browser.clazz;

import rexsee.core.browser.Browser;
import rexsee.core.lang.RexseeLanguage;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Message;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowserClient extends WebViewClient {
	private static final String TARGET_PREFIX = "#target=";
	private final Browser mBrowser;
	private final Context mContext;
	public BrowserClient(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
	}
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		if (url == null) return true;
		String target = "_self";
		if (url.contains(TARGET_PREFIX)) {
			String[] t = url.split(TARGET_PREFIX);
			target = t[1];
			url = t[0];
		}
		try {
			Browser targetBrowser = mBrowser;
			if (target.equalsIgnoreCase("_blank")) {
				if (mBrowser.windowListener != null) {
					Browser newBrowser = mBrowser.windowListener.getNewBrowser(mBrowser, false, true, true);
					if (newBrowser != null) targetBrowser = newBrowser;
				}
			}
			targetBrowser.function.load(url);
		} catch (Exception e) {
			mBrowser.exception("WebViewClient.shouldOverrideUrlLoading", e);
		}
		return true;
	}

	@Override
	public void onLoadResource(WebView view, String url) {
		mBrowser.loadResourceListeners.run(mContext, (Browser) view, url);
	}
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		HistoryItem item = mBrowser.history.getCurrentItem();
		url = (item == null) ? url : item.getUrl();
		mBrowser.pageStartedListeners.run(mContext, (Browser) view, url, favicon);
	}
	@Override
	public void onPageFinished(WebView view, String url) {
		if ((url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")) && !url.equals(mBrowser.history.getCurrentItem().getUrl())) return;
		//String updateLinkJs = "javascript: var allLinks = document.getElementsByTagName('a'); if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];var target = link.getAttribute('target'); if (target ) {link.href = link.href + '" + TARGET_PREFIX + "' + target ;}}}";
		String updateLinkJs = "javascript:";
		updateLinkJs += "var allLinks = document.getElementsByTagName('a'); ";
		updateLinkJs += "if (allLinks) {";
		updateLinkJs += "var i;for (i=0; i<allLinks.length; i++) {";
		updateLinkJs += "var link = allLinks[i];";
		updateLinkJs += "var target = link.getAttribute('target'); ";
		updateLinkJs += "if (target ) {";
		updateLinkJs += "var newHref = link.href;";
		updateLinkJs += "if( newHref == document.location.href ) newHref = newHref + '#';";
		updateLinkJs += "newHref = newHref + '" + TARGET_PREFIX + "' + target ;";
		updateLinkJs += "link.href = newHref;";
		updateLinkJs += "}";
		updateLinkJs += "}";
		updateLinkJs += "}";
		mBrowser.loadUrl(updateLinkJs);
		mBrowser.loadUrl("javascript: try { " + mBrowser.application.resources.prefix + "Browser.setSource(document.documentElement.outerHTML); } catch(e) {}");
		HistoryItem item = mBrowser.history.getCurrentItem();
		if (item != null) {
			item.finishTime = System.currentTimeMillis();
			int x = (int) (item.getScrollX() / mBrowser.application.screenDensity);
			int y = (int) (item.getScrollY() / mBrowser.application.screenDensity);
			if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
				//if (mBrowser.preload.contains(url)) {
				mBrowser.loadUrl("javascript: window.scrollTo(" + x + "," + y + ");");
				//}
			} else {
				mBrowser.loadUrl("javascript: window.scrollTo(" + x + "," + y + ");");
			}
		}
		mBrowser.pageReadyListeners.run(mContext, (Browser) view, url);
		mBrowser.eventList.run(mBrowser.EVENT_ONREXSEEREADY);
	}
	@Override
	public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
		view.stopLoading();
		mBrowser.progressListeners.run(mContext, (Browser) view, 100);
		mBrowser.errorListeners.run(mContext, (Browser) view, errorCode, description, failingUrl);
	}
	@Override
	public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
		handler.proceed();
	}

	@Override
	public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
		super.doUpdateVisitedHistory(view, url, isReload);
		if (isReload) return;
		if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {
			UrlListener listener = mBrowser.urlListeners.get(url);
			if (listener != null && listener.shouldAddToHistory(mContext, mBrowser, url)) mBrowser.history.add(url);
		}
	}
	@Override
	public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
		continueMsg.sendToTarget();
	}

	@Override
	public void onFormResubmission(WebView view, final Message dontResend, final Message resend) {
		mBrowser.application.confirm(RexseeLanguage.TITLE_ALERT, RexseeLanguage.MESSAGE_RESUBMIT, mContext.getString(android.R.string.ok), mContext.getString(android.R.string.cancel), new Runnable() {
			@Override
			public void run() {
				resend.sendToTarget();
			}
		}, new Runnable() {
			@Override
			public void run() {
				dontResend.sendToTarget();
			}
		});
	}

}
